import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:wanchong/app/app.dart';
import 'package:wanchong/app/im/chart.dart';
import 'package:wanchong/bean/im_android_entity.dart';
import 'package:wanchong/bean/im_conversation_android_entity.dart';
import 'package:wanchong/bean/im_conversation_entity.dart';
import 'package:wanchong/bean/im_entity.dart';
import 'package:wanchong/bean/im_user_info_entity.dart';

class ImCity extends StatefulWidget {
  @override
  _ImCityState createState() => _ImCityState();
}

class _ImCityState extends State<ImCity> {
  List<ImConversationEntity> _convations = [];
  List<ImConversationAndroidEntity> _androidConvations = [];
  List<Chats> _chats = [];
  @override
  void initState() {
    ///初始化会话列表
    _init();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: GestureDetector(
          onTap: () {
            Navigator.of(context).pop();
          },
          child: Container(
            color: Colors.transparent,
            // margin: EdgeInsets.only(
            //   left: 15.0,
            // ),
            child: Icon(Icons.chevron_left),
          ),
        ),
        title: Center(
          child: Text("同城消息"),
        ),
        centerTitle: true,
        elevation: 0.0,
        automaticallyImplyLeading: false,
      ),
      body: Container(
        margin: EdgeInsets.only(
          left: 15.0,
          right: 15.0,
        ),
        height: double.infinity,
        child: ListView.builder(
          itemBuilder: (BuildContext context, int index) => _item(index),
          itemCount: _chats.length,
        ),
      ),
    );
  }

  Widget _item(int index) {
    print("object");
    final Chats chat = _chats[index];
    return GestureDetector(
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(
            builder: (BuildContext context) => ImChat(
                  nick: chat.id,
                )));
      },
      child: Container(
        // color: Colors.red,
        height: 90.0,
        child: Row(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(right: 15.0),
              width: 50.0,
              height: 50.0,
              child: ClipOval(
                child: chat.face == "" || chat.face == null
                    ? Image.asset(
                        "assets/default.png",
                        fit: BoxFit.cover,
                      )
                    // : Image.asset(
                    //     "assets/default.png",
                    //     fit: BoxFit.cover,
                    //   )
                    : CachedNetworkImage(
                        imageUrl: chat.face,
                        fit: BoxFit.cover,
                      ),
              ),
            ),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Container(
                    width: double.infinity,
                    child: Text(
                      chat.nick == null || chat.nick == ""
                          ? chat.id
                          : chat.nick,
                      style: TextStyle(
                        color: Color(0xFF3C4450),
                        fontSize: 17.0,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 14.0,
                  ),
                  Container(
                    width: double.infinity,
                    child: Text(
                      chat.last,
                      style: TextStyle(
                        color: Color(0xFFB4BEC6),
                        fontSize: 14.0,
                      ),
                    ),
                  ),
                  // Text(chat.last)
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  _init() async {
    print("_init");
    var r = await dim.getConversations();
    List convations = json.decode(r);
    print(convations.length);
    if (Platform.isAndroid) {
      _androidConvations.addAll(convations
          .map((m) => ImConversationAndroidEntity.fromJson(m))
          .toList());
      print(_androidConvations.length);
      for (int i = 0; i < _androidConvations.length; i++) {
        ImConversationAndroidEntity item = _androidConvations[i];
        var r = await dim.getUsersProfile([item.peer]);
        List users = json.decode(r);
        ImUserInfoEntity user = ImUserInfoEntity.fromJson(users[0]);

        ///获取每一个会话的最后一条记录
        String c = await dim.getMessages(item.peer, 1);
        List msgs = json.decode(c);
        ImAndroidEntity im = ImAndroidEntity.fromJson(msgs[0]);
        _chats.add(Chats(
            id: item.peer,
            face: user.faceUrl,
            last: im.message.text,
            nick: user.nickName));
        setState(() {});
      }
    } else {
      _convations.addAll(
          convations.map((m) => ImConversationEntity.fromJson(m)).toList());
      for (int i = 0; i < _convations.length; i++) {
        ImConversationEntity item = _convations[i];
        var r = await dim.getUsersProfile([item.peer]);
        List users = json.decode(r);
        ImUserInfoEntity user = ImUserInfoEntity.fromJson(users[0]);

        ///获取每一个会话的最后一条记录
        String c = await dim.getMessages(item.peer, 1);
        List msgs = json.decode(c);
        ImEntity im = ImEntity.fromJson(msgs[0]);
        _chats.add(Chats(
            id: item.peer,
            face: user.faceUrl,
            last: im.message.text,
            nick: user.nickName));
      }
      setState(() {});
    }
    // print("setState");
    // print(_chats.length);
    // setState(() {});
  }
}

class Chats {
  String id;
  dynamic face;
  String last;
  String nick;
  Chats(
      {@required this.id,
      @required this.face,
      @required this.last,
      @required this.nick});
}
